The C++ standard libraries provide an extensive set of
input/output capabilities. This chapter discusses a range
of capabilities sufficient for performing most common
I/O operations and overviews the remaining
capabilities. Some of the features presented here were
discussed earlier in the text, but this chapter provides a
more complete discussion of the input/output
capabilities of C++.<br>
<spacer width=16 height=1>Many of the I/O features described here are object-
oriented. The reader should find it interesting to see
how such capabilities are implemented. This style of I/<br>
</page>
<page>
O makes use of other C++ features such as references,
function overloading, and operator overloading.<br>
<spacer width=16 height=1>As we will see, <a href="^Practice::c:s0p0"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>C++ uses <i>type safe I/O</i>. Each I/O
operation is automatically performed in a manner
sensitive to the data type. If an <a href="^Engineer::c:s0p0"><img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>I/O function has been
properly defined to handle a particular data type, then
that function is automatically called to handle that data
type. If there is no match between the type of the actual
data and a function for handling that data type, a
compiler error indication is set. Thus, improper data
cannot sneak through the system (as can occur in C--a
hole in C that allows for some rather subtle and often
bizarre errors).<br>
</page>
<page>
Users may specify I/O of <a href="^Engineer::c:s0p1"> <img src="bckgrnds/icons/seo_ico.gif" align=sidebar></a>user-defined types as well as
standard types. This <i>extensibility</i> is one of the most
in <a href="^Code::c:s0p2"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 11.5</a>. The <b>endl</b> stream manipulator issues a
newline character and, in addition, flushes the <a href="^Practice::c:s0p1"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>output
buffer (i.e., causes the output buffer to be output
immediately even if it is not full). The output buffer
may also be flushed simply by <br>
<font size=2><br></font><font size=11><pre>
cout << flush;<p>
</pre></font>
Stream manipulators are discussed in detail in <a href="#s6p0">Section
11.6</a>.<br>
<spacer width=16 height=1>Expressions can be output as shown in <a href="^Code::c:s0p3"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 11.6</a>.<br>
To <a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>read two integers, use the <b>cin</b> object and the
overloaded <b>>></b> <a href="^Errors::c:s0p1"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>stream-extraction operator as in <a href="^Code::c:s0p6"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig.
11.9</a>. Note that stream-extraction operations can also be
cascaded.<br>
<spacer width=16 height=1>The <a href="^Errors::c:s0p2"> <img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>relatively high precedence of the <b>>></b> and <b><<</b>
operators can cause problems. For example, the
program of <a href="^Code::c:s0p7"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 11.10</a> will not compile properly
without the parentheses around the conditional
expression. The reader should verify this. <br>
<spacer width=16 height=1>One popular way to <a href="^Portable::c:s0p0"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>input a series of values is to use the
stream-extraction operation in the loop-continuation
condition of a <b>while</b> loop. The extraction returns false <br>
(interpreted as <tt><b>false</b></tt>) when the user enters end-of-
file. <br>
<spacer width=16 height=1>In <a href="^Code::c:s0p8"> <img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 11.11</a>, <b>cin >> grade</b> can be used as a condition
because the base class <b>ios</b> (from which <b>istream</b> is
inherited) provides an overloaded cast operator that
converts a stream into a pointer of type <b>void *</b>. The
value of the pointer is 0 if an error occurred while <br>
attempting to read a value or the end-of-file indicator
was encountered. The compiler is able to use the <b>void *</b>
cast operator implicitly.<br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
<b>11.4.2 <b>get</b> and <b>getline</b> Member Functions</b><br>
The <b>get</b> member function with no arguments inputs one
character from the designated stream (even if this is
whitespace) and returns this character as the value of
the function call. This version of <b>get</b> returns <b>EOF</b> when
end-of-file on the stream is encountered. <br>
<spacer width=16 height=1> <a href="^Code::c:s0p9"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 11.12</a> demonstrates the use of member functions
<b>eof</b> and <b>get</b> on input stream <b>cin</b> and member function
<b>put</b> on output stream <b>cout</b>. The program first prints the
value of <b>cin.eof()</b>, i.e., <b>false</b> (<tt><b>0</b></tt> on the output) to show
that end-of-file has not occurred on <b>cin</b>. The user enters
a line of text and presses <i>Enter</i> followed by end-of-file
(<i><ctrl>-z</i> on IBM PC-compatible systems, <i><ctrl>-d</i> on <br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
UNIX and Macintosh systems). The program reads
each character and outputs it to <b>cout</b> using member
function <b>put</b>. When the end-of-file is encountered, the
<b>while</b> ends and <b>cin.eof()</b>--now <b>true</b>--is printed again
(<tt><b>1</b></tt> on the output) to show that end-of-file has been set
on <b>cin</b>. Note that this program uses the version of
<b>istream</b> member function <b>get</b> that takes no arguments
and returns the character being input.<br>
<spacer width=16 height=1>The <b>get</b> member function with a character argument
inputs the next character from the input stream (even if
this is a whitespace character) and stores it in the
character argument. This version of <b>get</b> returns 0 when
end-of-file is encountered; otherwise this version of <b>get</b> <br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
returns a reference to the <b>istream</b> object for which the
get member function is being invoked. <br>
<spacer width=16 height=1>A third version of the <b>get</b> member function takes three
arguments--a character array, a size limit, and a
delimiter (with default value '<b>\n</b>'). This version reads
characters from the input stream. It reads up to one less
than the specified maximum number of characters and
terminates, or terminates as soon as the delimiter is
read. A null character is inserted to terminate the input
string in the character array used as a buffer by the
program. The delimiter is not placed in the character
array, but does remain in the input stream (the delimiter
will be the next character read). Thus, the result of a <br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
second consecutive <b>get</b> is an empty line unless the
delimiter character is flushed from the input stream.
<a href="^Code::c:s0p10"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Figure 11.13</a> compares input using <b>cin</b> with stream
extraction (which reads characters until a whitespace
character is encountered) and input with <b>cin.get</b>. Note
that the call to <b>cin.get</b> does not specify a delimiter
character, so the default '<b>\n</b>' is used.<br>
<spacer width=16 height=1>The <b>getline</b> member function operates like the third
version of the <b>get</b> member function and inserts a null
character after the line in the character array. The
<b>getline</b> function removes the delimiter from the stream
(i.e., reads the character and discards it), but does not
store it in the character array. The program of <br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
<a href="^Code::c:s0p11"><img src="bckgrnds/icons/code_ico.gif" align=sidebar>Fig. 11.14</a> demonstrates the use of the <b>getline</b> member
function to input a line of text.<br>
</page>
<page pagename="11.4.2 <b>get</b> and <b>getline</b> Member Functions">
<b>Select the statement that generates a syntax error. </b><br>
<indent width=8 delay>* I/O operations are performed in a manner sensitive to
the type of the data. </indent>
<indent width=8 delay>* C++ I/O occurs in streams of bytes. A stream is simply a sequence of bytes. </indent>
<indent width=8 delay>* I/O mechanisms of the system move bytes from
devices to memory and vice versa in an efficient and
reliable manner. </indent>
<indent width=8 delay>* C++ provides "low-level" and "high-level" I/O capabilities. Low-level I/O-capabilities specify that some
number of bytes should be transferred device-to-memory or memory-to-device. High-level I/O is performed </indent>
</page>
<page>
<indent width=8 delay>* with bytes grouped into meaningful units such as integers, floats, characters, strings and user-defined types.</indent>
<indent width=8 delay>* C++ provides both unformatted I/O and formatted I/
O operations. Unformatted I/O transfers are fast, but
process raw data that is difficult for people to use. Formatted I/O processes data in meaningful units, but
requires extra processing time that can negatively
impact high-volume data transfers. </indent>
<indent width=8 delay>* Most C++ programs include the <b><iostream.h></b>
header file that contains basic information required for
all stream I/O operations. </indent>
<indent width=8 delay>* The <b><iomanip.h></b> header contains information for
formatted input/output with parameterized stream </indent>
</page>
<page>
<indent width=8 delay>* manipulators.</indent>
<indent width=8 delay>* The <b><fstream.h></b> header contains information for
file processing operations.</indent>
<indent width=8 delay>* The <b>istream</b> class supports stream input operations. </indent>
<indent width=8 delay>* The <b>ostream</b> class supports stream output operations. </indent>
<indent width=8 delay>* The <b>iostream</b> class supports both stream-input and
stream-output operations. </indent>
<indent width=8 delay>* The <b>istream</b> class and the <b>ostream</b> class are each
derived through single inheritance from the <b>ios</b> base
class. </indent>
<indent width=8 delay>* The <b>iostream</b> class is derived through multiple inheritance from both the <b>istream</b> class and the <b>ostream</b> </indent>
</page>
<page>
<indent width=8 delay>* class. </indent>
<indent width=8 delay>* The left shift operator (<b><<</b>) is overloaded to designate
stream output and is referred to as the stream-insertion
operator. </indent>
<indent width=8 delay>* The right shift operator (<b>>></b>) is overloaded to designate stream input and is referred to as the stream-extraction operator. </indent>
<indent width=8 delay>* The <b>istream</b> object <b>cin</b> is tied to the standard input
device, normally the keyboard. </indent>
<indent width=8 delay>* The <b>ostream</b> class object <b>cout</b> is tied to the standard
output device, normally the display screen. </indent>
<indent width=8 delay>* The <b>ostream</b> class object <b>cerr</b> is tied to the standard
error device. Outputs to <b>cerr</b> are unbuffered; each </indent>
</page>
<page>
<indent width=8 delay>* insertion to <b>cerr</b> appears immediately. </indent>
<indent width=8 delay>* Stream manipulator <b>endl</b> issues a newline character
and flushes the output buffer. </indent>
<indent width=8 delay>* The C++ compiler determines data types automatically for input and output. </indent>
<indent width=8 delay>* Addresses are displayed in hexadecimal format by
default. </indent>
<indent width=8 delay>* To print the address in a pointer variable, cast the
pointer to <b>void*</b>. </indent>
<indent width=8 delay>* Member function put outputs one character. Calls to
put may be cascaded. </indent>
<indent width=8 delay>* Stream input is performed with the stream-extraction
operator <b>>></b>. This operator automatically skips </indent>
</page>
<page>
<indent width=8 delay>* whitespace characters in the input stream. </indent>
<indent width=8 delay>* The <b>>></b> operator returns false when end-of-file is
encountered on a stream. </indent>
<indent width=8 delay>* Stream extraction causes <b>failbit</b> to be set for
improper input, and <b>badbit</b> to be set if the operation
fails.</indent>
<indent width=8 delay>* A series of values can be input using the stream-
extraction operation in a <b>while</b> loop header. The extraction returns 0 when end-of-file is encountered. </indent>
<indent width=8 delay>* The <b>get</b> member function with no arguments inputs
one character and returns the character; <b>EOF</b> is
returned if end-of-file is encountered on the stream. </indent>
<indent width=8 delay>* The <b>get</b> member function with an argument of type </indent>
</page>
<page>
<indent width=8 delay>* <b>char</b> inputs one character. <b>EOF</b> is returned when end-
of-file is encountered; otherwise, the <b>istream</b> object for
which the <b>get</b> member function is being invoked is
returned.</indent>
<indent width=8 delay>* The <b>get</b> member function with three arguments--a
character array, a size limit, and a delimiter (with
default value newline)--reads characters from the input
stream up to a maximum of limit - 1 characters and terminates, or terminates when the delimiter is read. The
input string is terminated with a null character. The
delimiter is not placed in the character array, but
remains in the input stream.</indent>
<indent width=8 delay>* The <b>getline</b> member function operates like the three </indent>
</page>
<page>
<indent width=8 delay>* argument <b>get</b> member function. The <b>getline</b> function
removes the delimiter from the input stream, but does
not store it in the string.</indent>
<indent width=8 delay>* Member function <b>ignore</b> skips the specified number
of characters (default is one character) in the input
stream; it terminates if the specified delimiter is
encountered (the default delimiter is <b>EOF</b>).</indent>
<indent width=8 delay>* The <b>putback</b> member function places the previous
character obtained by a <b>get</b> on a stream back onto that
stream. </indent>
<indent width=8 delay>* The <b>peek</b> member function returns the next character
from an input stream, but does not remove the character
from the stream.</indent>
</page>
<page>
<indent width=8 delay>* C++ offers type-safe input/output. If unexpected data
is processed by the <b><<</b> and <b>>></b> operators, various error
flags are set which the user may test to determine if an
I/O operation succeeded or failed. </indent>
<indent width=8 delay>* Unformatted I/O is performed with member functions <b>read</b> and <b>write</b>. These input or output some number of bytes to or from memory beginning at a
designated memory address. They are input or output as
raw bytes with no formatting. </indent>
<indent width=8 delay>* The <b>gcount</b> member function returns the number of
characters input by the previous read operation on that
stream.</indent>
<indent width=8 delay>* Member function read inputs a specified number of </indent>
</page>
<page>
<indent width=8 delay>* characters into a character array. <b>failbit</b> is set if fewer
than the specified number of characters are read.</indent>
<indent width=8 delay>* To change the base in which integers output, use the
manipulator <b>hex</b> to set the base to hexadecimal (base
16) or <b>oct</b> to set the base to octal (base 8). Use manipulator <b>dec</b> to reset the base to decimal. The base remains
the same until explicitly changed. </indent>
<indent width=8 delay>* The parameterized stream manipulator <b>setbase</b> also
sets the base for integer output. <b>setbase</b> takes one integer argument of <b>10</b>, <b>8</b>, or <b>16</b> to set the base. </indent>
<indent width=8 delay>* Floating-point precision can be controlled using
either the <b>setprecision</b> stream manipulator or the <b>precision</b> member function. Both set the precision for all </indent>
</page>
<page>
<indent width=8 delay>* subsequent output operations until the next precision-
setting call. The <b>precision</b> member function with no
argument returns the current precision value. </indent>
<indent width=8 delay>* Parameterized manipulators require the inclusion of
the <b><iomanip.h></b> header file. </indent>
<indent width=8 delay>* Member function <b>width</b> sets the field width and
returns the previous width. Values smaller than the field
are padded with fill characters. The field width setting
applies only for the next insertion or extraction; the
field width is implicitly set to <b>0</b> afterward (subsequent
values will be output as large as they need to be). Values larger than a field are printed in their entirety. Function <b>width</b> with no argument returns the current width </indent>
</page>
<page>
<indent width=8 delay>* setting. Manipulator <b>setw</b> also sets the width.</indent>
<indent width=8 delay>* For input, the <b>setw</b> stream manipulator establishes a
maximum string size; if a larger string is entered, the
larger line is broken into pieces no larger than the designated size.</indent>
<indent width=8 delay>* Users may create their own stream manipulators.</indent>
<indent width=8 delay>* Member functions <b>setf</b>, <b>unsetf</b>, and <b>flags</b> control the
flag settings.</indent>
<indent width=8 delay>* The <b>skipws</b> flag indicates that <b>>></b> should skip
whitespace on an input stream. The <b>ws</b> stream manipulator also skips over leading whitespace in an input
stream.</indent>
<br>
</page>
<page>
<indent width=8 delay>* Format flags are defined as an enumeration in class
<b>ios</b>.</indent>
<indent width=8 delay>* Format flags are controlled by the <b>flags</b> and <b>setf</b>
member functions, but many C++ programmers prefer
to use stream manipulators. The bitwise-or operation, <b>|</b>,
can be used to combine various options into a single
<b>long</b> value. Calling the <b>flags</b> member function for a
stream and specifying these "or-ed" options sets the
options on that stream and returns a <b>long</b> value containing the prior options. This value is often saved so <b>flags</b>
may be called with this saved value to restore the previous stream options.</indent>
<indent width=8 delay>* The <b>flags</b> function must specify a value representing </indent>
</page>
<page>
<indent width=8 delay>* the total settings of all the flags. The <b>setf</b> function with
one argument, on the other hand, automatically "ors"
the specified flags with the existing flag settings to
form a new format state. </indent>
<indent width=8 delay>* The <b>showpoint</b> flag is set to force a floating-point
number to be output with a decimal point and number
of significant digits specified by the precision. </indent>
<indent width=8 delay>* The <b>left</b> and <b>right</b> flags cause fields to be left-justified with padding characters to the right, or right-justified with padding characters to the left.</indent>
<indent width=8 delay>* The <b>internal</b> flag indicates that a number's sign (or
base when the flag <b>ios::showbase</b> is set) should be left-
justified within a field, magnitude should be right-justi</indent>
</page>
<page>
<indent width=8 delay>* fied, and intervening spaces should be padded with the
fill character. </indent>
<indent width=8 delay>* i<b>os::adjustfield</b> contains the flags <b>left</b>, <b>right</b>, and
<b>internal</b>. </indent>
<indent width=8 delay>* Member function <b>fill</b> specifies the fill character to be
used with <b>left</b>, <b>right</b>, and <b>internal</b> adjusted fields
(space is the default); the prior padding character is
returned. Stream manipulator <b>setfill</b> also sets the fill
character. </indent>
<indent width=8 delay>* Static member i<b>os::basefield</b> includes the <b>oct</b>, <b>hex</b>,
and <b>dec</b> bits to specify that integers are to be treated as
octal, hexadecimal, and decimal values, respectively.
Integer output defaults to decimal if none of these bits </indent>
</page>
<page>
<indent width=8 delay>* is set; stream extractions process the data in the form in
which it is supplied.</indent>
<indent width=8 delay>* Set the <b>showbase</b> flag to force the base of an integral
value to be output. </indent>
<indent width=8 delay>* Static data member i<b>os::floatfield</b> contains the flags
<b>scientific</b> and the <b>fixed</b>. Set the <b>scientific</b> flag to output
a floating-point number in scientific format. Set the
<b>fixed</b> flag to output a floating-point number with the
precision specified by the <b>precision</b> member function. </indent>
<indent width=8 delay>* The call <b>cout.setf(0, ios::floatfield) </b>restores the
default format for displaying floating-point numbers. </indent>
<indent width=8 delay>* Set the <b>uppercase</b> flag to force an uppercase <b>X</b> or<b> E</b>
to be output with hexadecimal integers or with scien</indent>
</page>
<page>
<indent width=8 delay>* tific notation floating-point values, respectively. When
set, the <b>ios::uppercase</b> flag causes all letters in a hexadecimal value to be uppercase.</indent>
<indent width=8 delay>* Member function <b>flags</b> with no argument returns the
<b>long</b> value of the current settings of the format flags.
Member function <b>flags</b> with a <b>long</b> argument sets the
format flags specified by the argument and returns the
prior flag settings. </indent>
<indent width=8 delay>* Member function <b>setf</b> sets the format flags in its
argument and returns the previous flag settings as a
<b>long</b> value.</indent>
<indent width=8 delay>* Member function <b>setf(long setBits, long resetBits)</b>
clears the bits of the <b>resetBits</b>, then sets the bit in <b>set</b></indent>
</page>
<page>
<indent width=8 delay>* <b>Bits</b>.</indent>
<indent width=8 delay>* Member function <b>unsetf</b> resets the designated flags
and returns the value of the flags prior to being reset.</indent>
<indent width=8 delay>* Parameterized stream manipulator <b>setiosflags</b> performs the same functions as member function <b>flags</b>. </indent>
<indent width=8 delay>* Parameterized stream manipulator <b>resetiosflags</b> performs the same functions as member function <b>unsetf</b>. </indent>
<indent width=8 delay>* The state of a stream may be tested through bits in
class <b>ios</b>. </indent>
<indent width=8 delay>* The <b>eofbit</b> is set for an input stream when end-of-file
is encountered during an input operation. The <b>eof</b> member function is used to determine if the <b>eofbit</b> has been
set.</indent>
</page>
<page>
<indent width=8 delay>* The <b>failbit</b> is set for a stream when a format error
occurred on the stream, but characters have not been
lost. The <b>fail</b> member function determines if a stream
operation has failed; it is normally possible to recover
from such errors.</indent>
<indent width=8 delay>* The <b>badbit</b> is set for a stream when an error occurred
that resulted in the loss of data. The <b>bad</b> member function determines if a stream operation has failed. Such
serious failures are normally nonrecoverable.</indent>
<indent width=8 delay>* The <b>good</b> member function returns true if the bad,
<b>fail</b>, and <b>eof</b> functions would all return false. I/O operations should only be performed on "good" streams.</indent>
<indent width=8 delay>* The <b>rdstate</b> member function returns the error state </indent>
</page>
<page>
<indent width=8 delay>* of the stream. </indent>
<indent width=8 delay>* Member function <b>clear</b> is normally used to restore a
stream's state to "good" so that I/O may proceed on that
stream.</indent>
<indent width=8 delay>* C++ provides the tie member function to synchronize <b>istream</b> and <b>ostream</b> operations to ensure that outputs appear before subsequent inputs. </indent>
</page>
</section>
<section type=Popup name=Debug title="Testing">
<page>
This chapter does not contain any Testing and Debugging tips.